package com.leyou.item.controller;

import com.leyou.common.pojo.PageResult;
import com.leyou.item.pojo.Brand;
import com.leyou.item.service.BrandService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/brand")
public class BrandController {

    @Autowired
    private BrandService brandService;

    @GetMapping("page")   //分页查询brand
    public ResponseEntity<PageResult> queryBrandByPage(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "rows", defaultValue = "5") Integer rows,
            @RequestParam(value = "sortBy", required = false) String sortBy,
            @RequestParam(value = "desc") Boolean desc,
            @RequestParam(value = "key", required = false) String key

    ) {
        PageResult<Brand> result = brandService.queryBrandByPage(page, rows, sortBy, desc, key);
        if (result == null || result.getItems() == null || result.getItems().size() < 1) {
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);
        }
        return ResponseEntity.ok(result);

    }

    //添加品牌
    @PostMapping
    public ResponseEntity<Void> saveBrand(Brand brand, @RequestParam("cids") List<Long> cids) {
        brandService.saveBrand(brand, cids);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    //修改品牌
    @PutMapping
    public ResponseEntity<Void> changeBrand(Brand brand, @RequestParam("cids") List<Long> cids) {
        brandService.changeBrand(brand, cids);
        return new ResponseEntity<>(HttpStatus.CREATED);
    }

    //删除品牌
    @DeleteMapping
    public ResponseEntity<Void> deleteBrand(@RequestBody Map<String, Long> map) {
        //System.out.println(map);
        Long bid = map.get("bid");
        brandService.deleteBrand(bid);
        return new ResponseEntity<>(HttpStatus.OK);
    }

    //根据分类id获取品牌
    @GetMapping("cid/{cid}")
    public ResponseEntity<List<Brand>> queryBrandByCategory(@PathVariable("cid") Long cid) {
        List<Brand> brands = brandService.queryBrandByCategory(cid);
        if (brands == null || brands.size() < 1) {
            return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
        }
        return ResponseEntity.ok(brands);
    }

    //根据品牌ids查询品牌
    @GetMapping("list")
    public ResponseEntity<List<Brand>> queryBrandByIds(@RequestParam("bids") List<Long> bids) {
        List<Brand> brands = brandService.queryBrandByIds(bids);
        if (brands == null || brands.size() == 0) {
            return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
        }
        return ResponseEntity.ok(brands);
    }
}
